<template>
    <div class="function">
        <div class="function-tools">
            <div class="function-tools-item">
                <el-button link @click="editFunctionView" :disabled="selectRowIndex===0">
                    <el-icon size="18" color="#337ecc">
                        <Edit/>
                    </el-icon>
                    <span style="font-size: 14px;">设计函数</span>
                </el-button>
            </div>
            <div class="function-tools-item">
                <el-button link @click="addFunctionView">
                    <el-icon size="18" color="#b88230">
                        <CirclePlus/>
                    </el-icon>
                    <span style="font-size: 14px;">新建函数</span>
                </el-button>
            </div>
            <div class="function-tools-item">
                <el-button link @click="deleteFunction" :disabled="selectRowIndex===0">
                    <el-icon size="18" color="#c45656">
                        <Remove/>
                    </el-icon>
                    <span style="font-size: 14px;">删除函数</span>
                </el-button>
            </div>
            <div class="function-tools-item">
                <el-button link @click="runFunction" :disabled="selectRowIndex===0">
                    <el-icon size="18" color="#409EFF">
                        <VideoPlay/>
                    </el-icon>
                    <span style="font-size: 14px;">运行函数</span>
                </el-button>
            </div>
            <div class="function-tools-item">
                <el-button link @click="showSearchInput" v-if="!searchInput">
                    <el-icon size="18">
                        <Search/>
                    </el-icon>
                </el-button>
                <el-input  v-model="searchContent" style="width: 240px"   size="small" prefix-icon="Search" clearable @change="searchTableName" @clear="clearSearch" v-else />
            </div>
        </div>
        <div class="function-table">
            <el-table :data="tableList"  v-loading="loading" border size="small" height="calc(100vh - 150px)" highlight-current-row @row-click="tableClickRow" @row-dblclick="dblSelectRow">
                <el-table-column type="index" width="50" fixed >
                    <template #default="scope">
                        <div style="width: 100%;display: flex;justify-content: flex-start;">
                            <div v-if="selectRowIndex===(scope.$index+1)"><el-icon size="18"><CaretRight /></el-icon></div>
                            <div>{{initIndex(scope.$index)}}</div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column   label="名"  prop="ROUTINE_NAME" show-overflow-tooltip />
                <el-table-column   label="更新日期"  prop="LAST_ALTERED" show-overflow-tooltip >
                    <template #default="scope">
                        {{formatTime(scope.row.LAST_ALTERED)}}
                    </template>
                </el-table-column>
                <el-table-column   label="函数类型" prop="ROUTINE_TYPE" show-overflow-tooltip />
                <el-table-column   label="决定性"  prop="IS_DETERMINISTIC" show-overflow-tooltip />
                <el-table-column   label="注释"  prop="ROUTINE_COMMENT" show-overflow-tooltip />
                <el-table-column   label="脚本"  prop="ROUTINE_DEFINITION" show-overflow-tooltip />
            </el-table>
        </div>
    </div>
    <el-dialog  v-model="saveVisible"  title="Tips"  width="500">
        <el-form :model="formData" label-width="auto" style="max-width: 600px">
            <el-form-item :label="keyInfo"  v-for="keyInfo in keyList">
                <el-input v-model="formData[keyInfo]" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="saveVisible = false">取消</el-button>
                <el-button type="primary" @click="confirmRunScript">确认</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="MysqlTableFunctionView">
    import {formatDate,formatTime} from "@/utils/dateUtils";
    const {proxy} = getCurrentInstance();
    const tableInfoData = reactive({
        loading:false,
        selectRowIndex:0,
        tableCount:0,
        selectRow:null,
        tableList: null,
        showSqlBox:false,
        keyList:[],
        connectionInfo:null,
        saveVisible:false,
        formData:{},
        showType:null,
        searchInput:false,
        searchContent:null,
    })
    const {loading,selectRowIndex,tableCount,tableList,selectRow,showSqlBox,keyList,connectionInfo,saveVisible,formData,showType,searchInput,searchContent}=toRefs(tableInfoData)

    function initData() {
        if(connectionInfo.value==null){
            let connect =proxy.$appStore.connectList.find(row=>row.id===(proxy.$route.query.connectId*1));
            connect.database=proxy.$route.query.databaseName
            connectionInfo.value=connect
        }
        let params={}
        params.databaseKey=proxy.$route.query.databaseName
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.getFunctionList,connectionInfo.value,params).then(res=>{
          if(res.code===200){
            tableCount.value=res.data.dataList.length;
            tableList.value=res.data.dataList;
          }else {
            proxy.$modal.alertError(res.message);
          }
        })
    }

    function initIndex(index) {
        let rowIndex = index + 1
        if(tableCount.value===0){
            loading.value = false
        }else if(rowIndex===tableCount.value){
            loading.value = false
        }
        return rowIndex;
    }

    function tableClickRow(row,column,event){
        selectRowIndex.value=(tableList.value.indexOf(row)+1)
        selectRow.value=row
        let params = {}
        params.databaseKey = proxy.$route.query.databaseName
        params.specificName = selectRow.value.SPECIFIC_NAME
        keyList.value=[]
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.getFunctionParamsList, connectionInfo.value, params).then(res => {
            res.data.dataList.forEach(row => {
                keyList.value.push(row.PARAMETER_NAME)
            })
        })
    }
    /**
     * 跳转函数视图
     * @param localSelectRow
     */
    function jumpFunctionView(localSelectRow) {
        let row={}
        Object.keys(proxy.$route.query).forEach(key=>{
            row[key]=proxy.$route.query[key]
        })
        if(localSelectRow){
            Object.keys(localSelectRow).forEach(key=>{
                row[key]=localSelectRow[key]
            })
        }
        proxy.$router.push({name:'functionInfo',query:row})
    }
    function editFunctionView(){
        if(!selectRow.value){
            proxy.$modal.msgError("请选择一条记录")
            return
        }
        jumpFunctionView(selectRow.value)
    }
    function addFunctionView(){
        jumpFunctionView()
    }
    function deleteFunction(){
        if(!selectRow.value){
            proxy.$modal.msgError("请选择一条记录")
            return
        }
        proxy.$modal.confirm('是否确认删除当前函数？').then(function() {
            let params={}
            params.runScript="DROP PROCEDURE IF EXISTS `"+selectRow.value.ROUTINE_SCHEMA+"`.`"+selectRow.value.ROUTINE_NAME+"`"
            return  proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole,connectionInfo.value,params);
        }).then(() => {
            initData()
            proxy.$modal.msgSuccess("删除成功")
        }).catch(() => {
        });
    }

    function runFunction(){
        if(!selectRow.value){
            proxy.$modal.msgError("请选择一条记录")
            return
        }
        if(keyList.value.length<1){
            let script="CALL "+selectRow.value.ROUTINE_NAME+"()"
            run(script)
        }else {
            saveVisible.value=true
        }
    }

    function confirmRunScript() {
        saveVisible.value=false
        let paramsArray=[]
        Object.keys(formData.value).forEach(key=>paramsArray.push(formData.value[key]))
        let script="CALL "+selectRow.value.ROUTINE_NAME+"("+paramsArray.join(",")+")";
        run(script)
    }

    function run(script) {
        let params={}
        params.runScript=script
        proxy.$userIpc.invoke(proxy.$ipcRouters.mysqlMng.runConsole,connectionInfo.value,params).then(res=>{
            if(res.code===200){
                if(Array.isArray(res.data.dataList)){
                    showType.value=1//列表
                    tableData.value=res.data.dataList
                    fieldData.value=res.data.fieldList
                }else {
                    showType.value=2//结果
                }
            }else{
                proxy.$modal.alertError(res.message)
            }
        })
    }

    function dblSelectRow(row, column, event){
        selectRow.value=row
        selectRowIndex.value=(tableList.value.indexOf(row)+1)
        jumpFunctionView(selectRow.value)
    }

    function showSearchInput(){
        searchInput.value=true
    }

    function searchTableName() {
        if(searchContent.value&&searchContent.value.trim().length>0){
            tableList.value=tableList.value.filter(row=>row.ROUTINE_NAME.includes(searchContent.value));
            tableCount.value=tableList.value.length
        }else {
            clearSearch()
            initData()
        }
    }

    function clearSearch() {
        searchInput.value=false;
        searchContent.value=null;
    }


    initData()

</script>

<style scoped lang="scss">
    .function{
        user-select: text;
    }
    .function-tools{
        display: flex;
        justify-content: flex-start;
        height: 32px;
        line-height: 32px;
    }
</style>
